<template>
  <div>
    <UploadExcel :on-success="onSuccess" />
  </div>
</template>

<script>
import { importEmployee } from '@/api/employees'
export default {
  methods: {
    async onSuccess({ results }) {
      const dictionary = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const data = []
      results.forEach(element => {
        // element // {姓名:xxx ....}
        const userInfo = {}
        Object.keys(element).forEach(key => {
          // Object.keys(element)  //姓名 ....        key // 姓名
          userInfo[dictionary[key]] = element[key]
          if (dictionary[key] === 'timeOfEntry' || dictionary[key] === 'correctionTime') {
            userInfo[dictionary[key]] = new Date(this.formatDate(element[key], '/'))
          }
        })
        data.push(userInfo)
        return data
      })
      try {
        console.log(this.$route.query)
        if (this.$route.query.type === 'employees') {
          await importEmployee(data)
          await this.$message.success('导入成功')
          setTimeout(() => {
            this.$router.back()
          }, 800)
        } else {
          await this.$message('未知文件格式')
        }
      } catch (error) {
        console.log(error)
      }
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
